package org.zjx.server;

import lombok.Getter;
import lombok.Setter;
import org.zjx.message.Message;

import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;

@Getter
public class ClientSession {
    private final String sessionId;
    private final Socket socket;
    private final PrintWriter writer;
    private final Date connectTime;

    @Setter
    private String clientId;
    @Setter
    private volatile boolean active = true;
    private Date lastActiveTime;

    public ClientSession(String sessionId, Socket socket, PrintWriter writer) {
        this.sessionId = sessionId;
        this.socket = socket;
        this.writer = writer;
        this.connectTime = new Date();
        this.lastActiveTime = new Date();
    }

    public boolean isActive() {
        return active && !socket.isClosed() && socket.isConnected();
    }

    /**
     * 向客户端发送消息（线程安全）
     */
    public void sendMessage(Message message) {
        if (!isActive()) return;

        synchronized (this) {
            if (!isActive()) return;

            try {
                writer.println(message.toJsonString());
                writer.flush();
                lastActiveTime = new Date();
            } catch (Exception e) {
                // 发送失败时标记为不活跃
                active = false;
            }
        }
    }

    public void updateLastActive() {
        lastActiveTime = new Date();
    }
}